Automated Image Optimization with WebP & AVIF via Nginx on Ubuntu 24.04

Giteqa

Greetings, friends!

You can rent a server with incredibly fast AMD Ryzen processors and configure instantaneous MySQL database response times, but if a user's browser has to download uncompressed 5–10 MB JPEG or PNG images when loading your homepage, the project will lag terribly.

In 2026, page load speed (specifically Google Core Web Vitals metrics like LCP) directly impacts search engine rankings and conversion rates. Modern formats such as WebP and the even more efficient AVIF have become the de facto standard for web graphics. They achieve 30–50% better compression than classic JPEG while preserving identical visual quality.

Attempting to convert images into new formats manually before uploading them to a website is a dead end for automation. The system must handle this task autonomously at the server level.

In this article, we will examine the technical mechanics of modern image formats and set up fully automated "on-the-fly" WebP/AVIF delivery using the Nginx web server.

Key Takeaways: Image Optimization Fundamentals

  • AVIF is the technological leader: AVIF compresses files significantly better than WebP, particularly across complex gradients and fine details, though it requires slightly more CPU encoder time.

  • Automation is essential: Combining Nginx with processing logic or background CLI tools (cwebp, avifenc) completely eliminates routine work for content managers.

  • Seamless fallback: Not all legacy browsers (or older operating systems) support AVIF. The server must check incoming browser Accept headers on the fly and serve AVIF to compatible clients, falling back to WebP or original JPEGs for others.

WebP vs. AVIF: What's the Difference in Bytes?

To understand why the industry is moving away from legacy formats, let's look at the underlying compression technologies. WebP is based on the VP8 video codec, while AVIF leverages the advanced compression capabilities of the AV1 codec.

File FormatAverage Size (vs. Original)Transparency (Alpha Channel)Animation SupportCPU Encoding Load
JPEG100% (Baseline)NoNoMinimal
WebP~65–70% (~30% smaller)YesYesLow
AVIF~40–50% (~50% smaller)YesYesHigh (requires strong CPU cores)

Automated Delivery Architecture at the Nginx Level

The most elegant and performant way to implement WebP/AVIF is using Nginx as a smart static proxy. We will not force the server to generate images dynamically the exact millisecond a user visits (which would create massive parasitic CPU spikes). Instead, we configure Nginx to check for pre-rendered, cached file variants on disk.

Step 1. Nginx Configuration (Inspecting Browser Headers)

When a browser requests an image, it sends an Accept header detailing supported MIME types (e.g., image/avif,image/webp,*/*).

Open your Nginx configuration file inside the http block (/etc/nginx/nginx.conf):

Nginx
map $http_accept $img_suffix {
    default       "";
    "~*image/avif" ".avif";
    "~*image/webp" ".webp";
}

This mapping checks incoming headers: if the browser supports AVIF, $img_suffix evaluates to .avif. If AVIF is unsupported but WebP is available, it evaluates to .webp.

Next, add smart static file delivery inside your virtual host (server block):

Nginx
location ~* ^.+\.(png|jpg|jpeg)$ {
    # Verify existence of pre-compressed file variants
    try_files $uri$img_suffix $uri =404;
    
    # Set proper caching headers
    expires 30d;
    add_header Cache-Control "public, no-transform";
    add_header Vary Accept;
}

How it works: A user requests photo.jpg. If their browser supports AVIF, Nginx uses try_files to check if photo.jpg.avif exists on disk. If found, it serves photo.jpg.avif seamlessly while keeping photo.jpg in the browser URL bar. If missing, it falls back to serving original photo.jpg.

Step 2. Background Conversion Script via Cron

Now, we set up a background task so the server automatically locates newly uploaded images (e.g., inside /var/www/uploads/) and generates .webp and .avif copies.

Install the necessary CLI utilities on Ubuntu 24.04:

Bash
sudo apt update
sudo apt install webp libavif-bin findutils -y

Create an automation Bash script:

Bash
mkdir -p ~/scripts && nano ~/scripts/img_compress.sh

Paste the following code:

Bash
#!/bin/bash

TARGET_DIR="/var/www/my_site/uploads"

# 1. Find all JPG/PNG files lacking WebP copies and convert them
find "$TARGET_DIR" -type f \( -name "*.jpg" -o -name "*.jpeg" -o -name "*.png" \) | while read -r img; do
    if [ ! -f "${img}.webp" ]; then
        cwebp -q 82 "$img" -o "${img}.webp" > /dev/null 2>&1
    fi
    
    # 2. Find and create AVIF copies
    if [ ! -f "${img}.avif" ]; then
        # -q 65 offers an optimal balance between visual quality and file size for AVIF
        avifenc -q 65 "$img" "${img}.avif" > /dev/null 2>&1
    fi
done

Make the script executable:

Bash
chmod +x ~/scripts/img_compress.sh

Add the script to crontab to process media hourly:

Bash
crontab -e

Append the execution line:

Plaintext
0 * * * * /bin/bash /root/scripts/img_compress.sh

Personal Experience

About ten years ago, I was brought in to optimize a heavy, slow-loading WordPress site. Beyond bloated plugins impacting performance, I noticed the website hosted an enormous volume of uncompressed JPEG images. This bloated the page size, pushing load times up to an unacceptable 5–7 seconds. I converted all images across the site into WebP format, which dramatically reduced load times and server overhead. If you want your site to load fast and rank well in search engines, compressing media assets is mandatory.

FAQ: Briefly About the Essentials

  • Does image conversion overload the server CPU?

    The cwebp utility is extremely fast and lightweight. However, encoding via avifenc is resource-intensive and can spike CPU core usage during batch compression of large images. This is why we run conversion tasks via background cron jobs (or off-peak hours) rather than generating files dynamically on HTTP request arrival.

  • Can I use third-party Nginx modules like ngx_pagespeed instead?

    While possible, dynamic modules can be unstable, require complex manual Nginx compilation from source, and introduce unpredictable RAM usage. Generating static file variants in the background via Bash scripts is the most resilient, performant, and reliable pattern in production architecture.

Conclusion

Automating WebP and AVIF adoption at the server level drastically reduces total page weight (often cutting media payload sizes by 2x to 3x). This speeds up site rendering on mobile networks (3G/4G), reduces bounce rates, and conserves server bandwidth.

Because graphic encoding utilities (especially avifenc) demand substantial processing power and generate disk I/O spikes during directory scans, running a stable backend requires high-performance hardware.

If you are optimizing online stores, media-heavy news portals, or B2B platforms, explore our NVME VPS / Dedicated Server services.


Article Author: Anatolie Cohaniuc